from fastapi import APIRouter, HTTPException, Depends, Query
from typing import List, Dict, Optional
from app.schemas.question import (
    QuestionCreate, 
    QuestionResponse, 
    TextQuestionRequest,
    TextQuestionResponse
)
from app.services.llm_service import LLMService
from app.services.question_service import QuestionService
from app.models.question import QuestionType, DifficultyLevel
from app.services.question_generator import QuestionGenerator

router = APIRouter()

@router.post(
    "/generate/{chapter_id}",
    response_model=List[QuestionResponse],
    tags=["Questions"],
    summary="为章节生成题目",
    description="根据章节内容自动生成指定类型和难度的题目"
)
async def generate_questions(
    chapter_id: int,
    question_types: List[str] = Query(
        default=[
            QuestionType.SINGLE_CHOICE,    # 单选题
            QuestionType.MULTIPLE_CHOICE,  # 多选题
            QuestionType.TRUE_FALSE,       # 判断题
            QuestionType.FILL_BLANK,       # 填空题
            QuestionType.SHORT_ANSWER,     # 简答题
        ],
        description="题目类型列表"
    ),
    difficulty: str = Query(
        default=DifficultyLevel.MEDIUM,
        description="题目难度",
        enum=[DifficultyLevel.EASY, DifficultyLevel.MEDIUM, DifficultyLevel.HARD]
    ),
    num_questions: int = Query(
        default=5,
        description="生成题目数量",
        ge=1,
        le=20
    )
):
    """
    为指定章节生成题目
    
    - **chapter_id**: 章节ID
    - **question_types**: 题目类型列表，可选值：
        - single_choice: 单选题
        - multiple_choice: 多选题
        - true_false: 判断题
        - fill_blank: 填空题
        - short_answer: 简答题
    - **difficulty**: 题目难度，可选值：
        - easy: 简单
        - medium: 中等
        - hard: 困难
    - **num_questions**: 生成题目数量
    """
    try:
        # 验证题目类型
        for qt in question_types:
            if not hasattr(QuestionType, qt.upper()):
                raise HTTPException(
                    status_code=400,
                    detail=f"Invalid question type: {qt}"
                )
        
        generator = QuestionGenerator()
        questions = await generator.generate_questions_for_chapter(
            chapter_id=chapter_id,
            question_types=question_types,
            difficulty=difficulty,
            num_questions=num_questions
        )
        return questions
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post(
    "/generate-batch",
    tags=["Questions"],
    summary="批量生成题目",
    description="为多个章节批量生成题目"
)
async def generate_questions_batch(
    chapter_ids: List[int],
    question_types: List[str] = Query(
        default=["选择题", "判断题", "简答题"],
        description="题目类型列表"
    ),
    difficulty: str = Query(
        default="中等",
        description="题目难度",
        enum=["简单", "中等", "困难"]
    ),
    num_questions_per_chapter: int = Query(
        default=5,
        description="每个章节生成的题目数量",
        ge=1,
        le=20
    )
):
    """
    批量为多个章节生成题目
    
    - **chapter_ids**: 章节ID列表
    - **question_types**: 题目类型列表
    - **difficulty**: 题目难度
    - **num_questions_per_chapter**: 每个章节生成的题目数量
    """
    try:
        generator = QuestionGenerator()
        results = await generator.generate_questions_batch(
            chapter_ids=chapter_ids,
            question_types=question_types,
            difficulty=difficulty,
            num_questions_per_chapter=num_questions_per_chapter
        )
        return results
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/generate/from-text", response_model=TextQuestionResponse)
async def generate_questions_from_text(
    request: TextQuestionRequest
):
    """
    基于文本内容生成题目
    
    Args:
        content: 文本内容
        question_types: 题目类型列表
        difficulty: 难度级别
        num_questions: 生成题目数量
    
    Returns:
        生成的题目列表
    """
    try:
        # 验证参数
        # if not all(qt in QuestionType.__dict__ for qt in request.question_types):
        #     raise HTTPException(status_code=400, detail="无效的题目类型")
        # if request.difficulty not in DifficultyLevel.__dict__:
        #     raise HTTPException(status_code=400, detail="无效的难度级别")
            
        # 生成题目
        llama_service = LLMService()
        questions = await llama_service.generate_questions_from_text(
            text=request.content,
            question_types=request.question_types,
            difficulty=request.difficulty,
            num_questions=request.num_questions
        )
        
        return {"questions": questions["questions"]}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e)) 